package server

import (
	v1 "geekbang-go-homework/week04/api/order/v1"
	"geekbang-go-homework/week04/internal/conf"
	"geekbang-go-homework/week04/pkg/transport/grpc"

	"google.golang.org/grpc/grpclog"
)

func NewGrpcServer(conf *conf.Bootstrap, log grpclog.LoggerV2, server v1.OrderApiServer) *grpc.Server {
	s := grpc.NewServer(append([]grpc.ServerOption{
		grpc.WithLog(log),
	}, grpcServerOptions(conf)...)...)
	v1.RegisterOrderApiServer(s, server)
	return s
}

func grpcServerOptions(conf *conf.Bootstrap) []grpc.ServerOption {
	if conf.GetServer().GetGrpc() == nil {
		return nil
	}
	var opts []grpc.ServerOption
	if conf.Server.Grpc.Network != "" {
		opts = append(opts, grpc.WithNetwork(conf.Server.Grpc.Network))
	}
	if conf.Server.Grpc.Addr != "" {
		opts = append(opts, grpc.WithAddress(conf.Server.Grpc.Addr))
	}
	if conf.Server.Grpc.GetTimeout().IsValid() {
		opts = append(opts, grpc.WithTimeout(conf.Server.Grpc.Timeout.AsDuration()))
	}
	return opts
}
